//
//  CYImageAvatarBrowser.m
//  RongYunChatDemo
//
//  Created by apple on 16/3/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "CYImageAvatarBrowser.h"

static UIImageView *orginImageView;
@implementation CYImageAvatarBrowser

-(void)showImage:(UIImageView *)avatarImageView with:(NSString *)imageUrl {
    UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]];
    orginImageView = avatarImageView;
    orginImageView.alpha = 0;
    UIWindow *window=[UIApplication sharedApplication].keyWindow;
    UIView *backgroundView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    CGRect oldframe=[avatarImageView convertRect:avatarImageView.bounds toView:window];
    backgroundView.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.7];
    backgroundView.alpha=1;
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:oldframe];
    //    [imageView setImageWithURL:[NSURL uRLWithString:@"http://rongcloud-image.ronghub.com/image_jpeg__RC-2016-06-07_48_1465298952?e=2147483647&token=CddrKW5AbOMQaDRwc3ReDNvo3-sL_SO1fSUBKV3H:kuPOWI1NwZQn77vkfAw8ksmmEXo="]];
    imageView.image = image;
    imageView.tag=1;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [backgroundView addSubview:imageView];
    [window addSubview:backgroundView];
    _backgroundView = backgroundView;
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
    [_backgroundView addGestureRecognizer: tap];
    [[NSUserDefaults standardUserDefaults] setObject:@"yes" forKey:@"nowimage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [UIView animateWithDuration:0.1 animations:^{
        imageView.frame=CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
        backgroundView.alpha=1;
    } completion:^(BOOL finished) {
        
    }];
    
}

- (void)hideImage:(UITapGestureRecognizer*)tap{
    UIView *backgroundView=tap.view;
    UIImageView *imageView=(UIImageView*)[tap.view viewWithTag:1];
    [UIView animateWithDuration:0.15 animations:^{
        imageView.frame=[orginImageView convertRect:orginImageView.bounds toView:[UIApplication sharedApplication].keyWindow];
    } completion:^(BOOL finished) {
        [_backgroundView removeFromSuperview];
        [[NSUserDefaults standardUserDefaults] setObject:@"no" forKey:@"nowimage"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        orginImageView.alpha = 1;
        backgroundView.alpha=0;
        if ([self.delegate respondsToSelector:@selector(cyimgeShowOver)]) {
            [self.delegate cyimgeShowOver];
        }
    }];
}
@end
